import PropTypes from 'prop-types'
import React, {memo, useEffect, useRef} from 'react'
import {IndicatorWrapper} from "@/base-ui/indicator/style";

const Indicator = memo((props) => {

    // 当前选中
    const {selectIndex = 0} = props;
    const contentRef = useRef();
    useEffect(() => {

        //  1.获取selectIndex 元素需要滚动的位置
        const selectItemEl = contentRef.current?.children[selectIndex];
        const itemLeft = selectItemEl.offsetLeft;
        const itemWidth = selectItemEl.clientWidth;
        // 2.获取content 宽度
        const contentWidth = contentRef.current?.clientWidth;
        const contentScroll = contentRef.current.scrollWidth;
        // 3.滚动距离
        let distance = itemLeft + itemWidth * 0.5 - contentWidth * 0.5;
        console.log('distance', distance)
        //左边边界
        if (distance < 0) distance = 0;
        // 右边边界
        const totalDistance = contentScroll - contentWidth
        if (distance > totalDistance) distance = totalDistance;
        contentRef.current.style.transform = `translate(${-distance}px)`;

    }, [selectIndex]);
    return (
        <IndicatorWrapper>
            <div className="i-content" ref={contentRef}>
                {props.children}
            </div>
        </IndicatorWrapper>
    )
})
Indicator.propTypes = {}
export default Indicator
